from flask import render_template, g, redirect, request, jsonify, session, current_app, abort

from info import constants, db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id, News.status==0).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
            }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """查看其他用户信息"""
    user = g.user
    other_id = request.args.get('user_id')

    if not other_id:
        abort(404)
    try:
        other_id = int(other_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    other = None  # type:User
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data={
        "user": user if user else None,
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }

    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
        }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    """用户发布的新闻的列表

    :return:
    """
    # 从前端获取页数
    p = request.args.get('p', 1)

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        pag = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = pag.items
        # 获取当前页
        current_page = pag.page
        # 获取总页数
        total_page = pag.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news in news_li:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "current_page":current_page,
        "total_page":total_page,
        "news_dict_li":news_dict_li
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods = ['GET', 'POST'])
@user_login_data
def news_release():
    """发布新闻

    :return:
    """

    if request.method == 'GET':
        # 查询新闻分类
        category = []
        try:
            category = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_li = []
        for categories in category:
            category_li.append(categories.to_dict())

        category_li.pop(0)

        return render_template('news/user_news_release.html', data={"category_li":category_li})

    # POST
    # 1. 获取要提交的数据
    title = request.form.get("title")
    # 来源
    source = "个人发布"
    # 新闻摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 索引图片
    index_image = request.files.get("index_image")
    # 新闻分类_id
    category_id = request.form.get("category_id")
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)

    # 1.2 尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="图片有误")

    # 使用七牛云上传图片
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")

    # 3. 初始化新闻模型，并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    # 4. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/user_collection')
@user_login_data
def user_collection():
    """用户收藏界面

    :return:
    """

    # 1. 获取页数
    p = request.args.get('p', 1)

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 获取用户收藏信息
    user = g.user
    collections = []
    current_page = 1
    total_page = 1
    try:
        pag = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = pag.items
        # 获取当前页
        current_page = pag.page
        # 获取总页数
        total_page = pag.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": collection_dict_li
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=['GET','POST'])
@user_login_data
def pass_info():
    """修改密码

    :return:
    """
    # 1. 获取用户登录信息
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # POST
    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 校验旧密码
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 保存新密码
    user.password = new_password

    # 响应
    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/pic_info', methods=['GET','POST'])
@user_login_data
def pic_info():
    """用户头像

    :return:
    """

    # 1. 获取用户登录信息
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

    # POST
    # 2.上传头像
    # 获取上传文件
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 使用封装好的七牛云进行上传
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    # 保存图片地址到数据库
    user.avatar_url = key

    # 响应
    return jsonify(errno=RET.OK, errmsg='OK！', data ={'avatar_url':constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=['GET','POST'])
@user_login_data
def base_info():
    """用户基本信息
    1. 获取用户登录信息
    2. 获取到传入参数
    3. 更新并保存数据
    4. 返回结果
    :return:
    """

    # 1. 获取用户登录信息
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={"user": g.user.to_dict()})

    # 2. 获取到传入参数
    data_dict = request.json
    nick_name = data_dict.get('nick_name')
    signature = data_dict.get('signature')
    gender = data_dict.get('gender')

    if not all([data_dict, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足！')

    if gender not in (['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 更新并保存数据
    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    # 4. 返回结果
    return jsonify(errno=RET.OK, errmsg='OK！')


@profile_blu.route('/info')
@user_login_data
def user_info():

    user = g.user
    if not user:
        return redirect('/')

    data={
        "user": user.to_dict()
    }
    return render_template('news/user.html', data=data)